//
//  APIRequestClient.m
//  XWKit
//
//  Created by xiaowuxiaowu on 16/3/26.
//  Copyright © 2016年 xiaowuxiaowu. All rights reserved.
//




#import "APIRequestClient.h"
#import "UNOpenUDID.h"
@implementation APIRequestClient

+(NSString *)baseUrl{
  return YPBaseUrl;
}
const char udidKey = '\0';

+(AFHTTPSessionManager *)shareManager{
   static AFHTTPSessionManager *manager ;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:YPBaseUrl]];
        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json",nil];
         objc_setAssociatedObject([XWCommon shareAppDelegate], &udidKey, [UNOpenUDID value], OBJC_ASSOCIATION_COPY);
    });
    return manager;
}

-(void)POST:(NSString * )urlString parameters:( id)parameters
          progress:( void (^)( NSProgress * uploadProgress)) uploadProgress
           success:(successBlock)success
           failure:(failureBlock)failure nonetWork:(nonetWorkBlock)nonetWorkBlock{

    
    if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable){
        nonetWorkBlock(nil,nil);
        return;
        
    }
    
    DLog(@"请求路径=%@ \n 请求参数=%@\n---%@",[YPBaseUrl  stringByAppendingString:urlString],parameters,[LoginModel shareLoginModel].access_token);
    
    AFHTTPSessionManager *manager = [APIRequestClient shareManager];
    if([LoginModel shareLoginModel].access_token.length >0)
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",[LoginModel shareLoginModel].access_token] forHTTPHeaderField:@"Authorization"];
    
    else{
        [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
    }
//
//    [manager.requestSerializer setValue:objc_getAssociatedObject([XWCommon shareAppDelegate], &udidKey) forHTTPHeaderField:@"uuid"];
//    [manager.requestSerializer setValue:@"1.0" forHTTPHeaderField:@"versionCode"];
//    [manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"app"]; // 2 = iOS
   self.dataTask = [manager POST:urlString parameters:parameters progress:uploadProgress success:^(NSURLSessionDataTask *  task, id  responseObject) {
       
        Responese* response = [Responese yy_modelWithJSON:responseObject];
        DLog(@"获取信息： message= %@  \n信息详情：  %@  \n %@",response.message, [response yy_modelToJSONString],response);
           if(response.status)
          success(task,responseObject,response);
          else
          failure(task,responseObject,response);
     
           
       
    } failure:^(NSURLSessionDataTask *  task, NSError *  error) {
        
         DLog(@"网络失败 \n信息详情：  %@  \n",error);
         nonetWorkBlock(task,error);
        
    }];
    
}

-(void)GET:(NSString * )urlString parameters:( id)parameters
   progress:( void (^)( NSProgress * uploadProgress)) uploadProgress
    success:(successBlock)success
    failure:(failureBlock)failure nonetWork:(nonetWorkBlock)nonetWorkBlock{
    
    
    if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable){
        nonetWorkBlock(nil,nil);
        return;
        
    }
    
    
    DLog(@"请求路径=%@ \n 请求参数=%@\n---token---%@",[YPBaseUrl  stringByAppendingString:urlString],parameters,[LoginModel shareLoginModel].access_token);
    
    AFHTTPSessionManager *manager = [APIRequestClient shareManager];
    if([LoginModel shareLoginModel].access_token.length >0){
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",[LoginModel shareLoginModel].access_token] forHTTPHeaderField:@"Authorization"];
    }else{
        [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
    }
    //
    self.dataTask = [manager GET:urlString parameters:parameters progress:uploadProgress success:^(NSURLSessionDataTask *  task, id  responseObject) {
        
        
        id x = [responseObject yy_modelToJSONObject];
        
        Responese* response = [Responese yy_modelWithJSON:responseObject];
        DLog(@"获取信息： message= %@  \n信息详情：  %@  \n%@",response.message, [response yy_modelToJSONString],x);
        if(response.status)
            success(task,responseObject,response);
        else
            failure(task,responseObject,response);
        
        
    } failure:^(NSURLSessionDataTask *  task, NSError *  error) {
        
        DLog(@"网络失败 \n信息详情：  %@  \n",error);
        nonetWorkBlock(task,error);
        
    }];
    
}



-(void)other_post:(NSString * )urlString parameters:( id)parameters
         progress:( void (^)( NSProgress * uploadProgress)) uploadProgress
          success:(successBlock)success
          failure:(failureBlock)failure{
    
    
    AFHTTPSessionManager *_manager = [APIRequestClient shareManager];
    
    DLog(@"-------------------请求连接--------------------------\n %@ \n传入字典 = %@",urlString,parameters);
    
    
    self.dataTask = [_manager POST:urlString parameters:parameters progress:uploadProgress success:^(NSURLSessionDataTask *  task, id  responseObject) {
        
        DLog(@"\n\n----%@",[responseObject yy_modelToJSONObject]);
        success(task,[responseObject yy_modelToJSONObject],[Responese new]);
        
    } failure:^(NSURLSessionDataTask *  task, NSError *  error) {
        
        failure(task,error,[Responese new]);
        DLog(@"error = %@",error);
    }];
    
    
}
-(void)other_get:(NSString * )urlString parameters:( id)parameters
        progress:( void (^)( NSProgress * uploadProgress)) uploadProgress
         success:(successBlock)success
         failure:(failureBlock)failure{
    
    
    AFHTTPSessionManager *_manager = [APIRequestClient shareManager];
    
    DLog(@"-------------------请求连接--------------------------\n %@ \n传入字典 = %@",urlString,parameters);
    
    
    self.dataTask = [_manager GET:urlString parameters:parameters progress:uploadProgress success:^(NSURLSessionDataTask *  task, id  responseObject) {
        
        
        DLog(@"成功\n\n----%@",[APIRequestClient tp_dictionaryWithJSON:responseObject]);
        success(task,[APIRequestClient tp_dictionaryWithJSON:responseObject],[Responese new]);
        
        
        
    } failure:^(NSURLSessionDataTask *  task, NSError *  error) {
        
        failure(task,error,[Responese new]);
        DLog(@"失败error = %@",error);
    }];
    
    
}









- (void)downloadTaskWithUrl:(NSString *)urlString
                       progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
                    destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
              completionHandler:(void (^)(NSURLResponse *response, NSURL * filePath, NSError *  error))completionHandler{
    
    
//    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
//    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",nil];
//
//  
    AFHTTPSessionManager *manager = [APIRequestClient shareManager];
    
    NSURL *URL = [NSURL URLWithString:[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet]];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    self.downLoadTask = [manager downloadTaskWithRequest:request progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
    
    [_downLoadTask resume];
    

}

- (NSURLSessionUploadTask *)uploadTaskWithUrlString:(NSString *)urlString parameters:( id)parameters  mimeType:(NSString *)mimeType sourceData:(NSData*)sourceData
                                           progress:(void (^)(NSProgress * downloadProgress)) downloadProgressBlock
                                  completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler{
    
    
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",nil];
    
    
    NSMutableURLRequest *request = [manager.requestSerializer
                                    multipartFormRequestWithMethod:@"POST"
                                    URLString:urlString
                                    parameters:parameters
                                    constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                                        [formData appendPartWithFileData:sourceData name:@"file" fileName:@"file" mimeType:mimeType];
                                    } error:nil];
    
    NSURLSessionUploadTask *tak = [manager uploadTaskWithStreamedRequest:request progress:downloadProgressBlock completionHandler:completionHandler];
    [tak resume];
    return tak;

}
-(void)uploadTaskWithStreamedRequest{
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
    } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {
                      dispatch_async(dispatch_get_main_queue(), ^{

                      //    [progressView setProgress:uploadProgress.fractionCompleted];
                      });
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          NSLog(@"Error: %@", error);
                      } else {
                          NSLog(@"%@ %@", response, responseObject);
                      }
                  }];
    
    [uploadTask resume];
}

+ (NSDictionary *)tp_dictionaryWithJSON:(id)json {
    if (!json || json == (id)kCFNull) return nil;
    NSDictionary *dic = nil;
    NSData *jsonData = nil;
    if ([json isKindOfClass:[NSDictionary class]]) {
        dic = json;
    } else if ([json isKindOfClass:[NSString class]]) {
        jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding];
    } else if ([json isKindOfClass:[NSData class]]) {
        jsonData = json;
    }
    if (jsonData) {
        dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
        if (![dic isKindOfClass:[NSDictionary class]]) dic = nil;
    }
    return dic;
}


@end




@implementation Responese


@end

